let app = getApp();
let httptool = require("../../utils/zry.httptool.js");
let tabjs = require("../../utils/tab.js");
Page({
  data: {
    tabNum: 1,  //tab编号
    topics: [],
    localCityName: '本市擂盟',//tab选项卡城市擂盟名称
    page: { PageIndex: 0, PageSize: 10 },
    loading:true,
    thumbState:false,//点赞的状态
    zanImg:'../../images/zan.png',
    authTokenRegister:'',//是否注册
    compuInfo:'',//提示注册的信息
    activeIndex:'2',
    noData:false,
    msgprop: '',//消息提示
    delArea:true,//删除提示框
    delforums:{},//删除帖子是需要的参数
    index:0,
    image:'',//默认图片
    imgLength:false,
    imgshow:false   
  },
  onLoad: function (options) {
    let that = this;
    let circleName = app.getStorage('CircleName');
    circleName = circleName == null || circleName == "" ? "本市擂盟" : circleName;
    that.setData({ localCityName: circleName });
    that.getTopics();
  },
 
  onShow: function () {
    // let that = this;
    // if (wx.getStorageSync("tabNum"))
    // {
    //   that.setData({ tabNum: wx.getStorageSync("tabNum") });
    // }
  },
  loadImg:function(e){
    let that=this;
    let images=[];
    let errortopic=e.target.dataset.errortopic;
    let errorImgIndex= e.target.dataset.errorimg; //获取循环图片的下标
    let imgObject="that.data.topics["+errortopic+"].ImgList";//carlistData为数据源，对象数组
    let errImgs=that.data.topics[errortopic].ImgList;
    for(let i=0; i<errImgs.length;i++){
          errImgs[i]='../../images/defimg.png';
          images.push(errImgs[i]);
    }
    let  errorImg={}
    that.data.topics[errortopic].ImgList=images;
  },
  onPullDownRefresh: function () {//下拉刷新
    let that = this;
    wx.stopPullDownRefresh();
    let page = { PageIndex: 0, PageSize: 10 };
    that.setData({ topics: [], page: page, noData:false });
    that.getTopics();
  },
  onReachBottom: function () {//上拉加载
    let that = this;
    that.getTopics();
  },
  tabClick: function (e) {    //全国擂盟，城市擂盟，自建门派导航切换事件
    let that = this;
    that.data.page={PageIndex:0, PageSize: 10};
    that.setData({ 
      tabNum: e.currentTarget.dataset.num,
      topics:[],
      loading:true,
      page: that.data.page,
      noData: false
    });
    that.getTopics();
  },

  getTopics: function (e) {//获取帖子列表
    let that = this;
    let param = {};
    param.UserId = app.getStorage('customerId');
    param.TopicType = that.data.tabNum;
    param.PageIndex = that.data.page.PageIndex + 1;
    param.PageSize = that.data.page.PageSize;
    app.showLoading();
    if (param.TopicType == 1) {
      httptool.ajaxBasePost("api/Topic/GetTopic", param, function (res) { 
        that.backTopics(res, that);
      },function () { wx.hideLoading(); });
    } else {
      httptool.ajaxPost("api/Topic/GetTopicsNeedLogin", param, function (res) { 
        that.backTopics(res,that); 
      },function () { wx.hideLoading(); });
    }
  },
  backTopics: function (res,that){
    let circleName = app.getStorage('CircleName');
    circleName = circleName == null || circleName == "" ? "本市擂盟" : circleName;
    that.setData({ localCityName: circleName });
    if (res.suc) {
      let data = app.notNull(res.data, []);
      if (data.length > 0) {
        for (let i = 0; i < data.length;i++){

          data[i].CreateDate=app.editTime(data[i].CreateDate);
        }
        that.data.page.PageIndex += 1;
        data = that.data.topics.concat(data);
        that.setData({ topics: data, page: that.data.page });
      }
      else if (that.data.page.PageIndex < 1) {
        that.setData({ noData: true });
      }
    } else {
      that.setData({ noData: false });
      app.showNotify(that, res.msg);
    }
    wx.hideLoading();
  },
  enterDetail: function (e) {//点击帖子进入对应的帖子详情
    let forumId = e.currentTarget.dataset.id;
    let UserId=app.getStorage('customerId') || '0';
  //  wx.setStorageSync("tabNum", this.data.tabNum);
    wx.navigateTo({
      url: '../detailPost/detailPost?ID=' + forumId + "&UserId=" + UserId + "&fromindex=" + 1,
    })
  },
  enterCircle:function(e){//点击进入对应的擂盟详情
    let id=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/search/search?ID='+id+"&UserId="+app.getStorage('customerId')+"&eId="+1,
    });
  },
  enterComment:function(e){////点击评论按钮进入对应的帖子详情，并调出回复框
    let forumId = e.currentTarget.dataset.id;
    let UserId = app.getStorage('customerId') || '0';
  //  wx.setStorageSync("tabNum", this.data.tabNum);
    wx.navigateTo({
      url: '../detailPost/detailPost?ID=' + forumId + "&dtype=" + 1 + "&UserId=" + UserId + "&fromindex=" + 1,
    })
  },
  Posted: function () {//发帖
    let that = this;
    httptool.login(function(){
      let UserId=app.getStorage('customerId');
      let CircleId = that.data.tabNum;
   //   wx.setStorageSync("tabNum", that.data.tabNum);
      httptool.ajaxPost("api/Customer/GetMyRights", { UserId: UserId }, function (res) {
        if (res.suc) {
            if(res.data.IsAddTopic==true){
                wx.navigateTo({
                  url: '../share/share?CircleId=' + CircleId,
                });
            }else{
                app.showNotify(that, "级别不够，不能发帖哦！");
            }
        } else {
          app.showNotify(that, res.msg);
        }
      });
    });   
  },
  searchBtn: function () {
 //   wx.setStorageSync("tabNum", this.data.tabNum);
    wx.navigateTo({
      url: '../search/search?stype='+1,
    });
  },
  buildPart: function () {/*点击建盟事件*/
    let that=this;
    httptool.login(function(){
      let UserId=app.getStorage('customerId');
      httptool.ajaxPost("api/Customer/GetMyRights", { UserId: UserId }, function (res) {
        if (res.suc) {
          if (res.data.IsAddCircle == false && res.data.IsAddTopic == true) {
            app.showNotify(that, res.data.Msg);
            return false;
          } else if (res.data.IsAddCircle == false && res.data.IsAddTopic == false){
            app.showNotify(that, res.data.Msg);
            return false;
          }
          else if(res.data.IsAddCircle==true && res.data.IsAddTopic==true){
       //     wx.setStorageSync("tabNum", that.data.tabNum);
            wx.navigateTo({
              url: '../buildpart/buildpart',
            });
          }
        } else {
          app.showNotify(that, res.msg);
        }
      });
    }); 

  },
  enterRanking:function(e){//点击进入擂手榜
    wx.setStorageSync("tabNum", this.data.tabNum);
    wx.redirectTo({
      url: '../leiList/leiList',
    });
  },
  thumbs_up: function (e) {//点赞事件
    let that = this;
    let isup=e.currentTarget.dataset.isup;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let likeTimes = e.currentTarget.dataset.liketimes;
    let thumbs = {};
    thumbs.UserId = app.getStorage('customerId');
    thumbs.TopicId = id;
      httptool.ajaxPost("api/TopicZan/AddorDelLike", thumbs, function (res) {
        if (res.suc) {
          if(res.data==1){
            that.data.topics[index].LikeTimes = likeTimes + 1;
            that.setData({ topics: that.data.topics,thumbState:true,zanImg:'../../images/zan_a.png'});
            wx.showToast({
              title: "点赞成功",
              duration: 1000,
              icon: "success"
            })
          }else if(res.data==0){
            that.data.topics[index].LikeTimes = likeTimes - 1;
            that.setData({ topics: that.data.topics,thumbState:false,zanImg:'../../images/zan.png' });
            wx.showToast({
              title: "取消点赞",
              duration: 1000,
              icon: "success"
            })
          }
        } else {
            app.showNotify(that, res.msg);
        }
      });
  },
  friendDetail:function(e){//点击头像进入某人的详情页，查看对方信息，帖子
    let that=this;
    let ToUserId = e.currentTarget.dataset.creatid;
  //  wx.setStorageSync("tabNum", this.data.tabNum);
    wx.navigateTo({
      url: '../followdetail/followdetail?ToUserId='+ToUserId,
    });
  },
  enterForward:function(e){//点击进入转发页面
    let that=this;
    let fourumId=e.currentTarget.dataset.id;
    let Reference = e.currentTarget.dataset.reference;
 //   wx.setStorageSync("tabNum", that.data.tabNum);
    if(Reference!=0){
      wx.navigateTo({
        url: '../forward/forward?fourumId='+Reference,
      });
    }else{
      wx.navigateTo({
        url: '../forward/forward?fourumId=' + fourumId,
      });
    }

  },
  goToforwardForum:function(e){//点击转发的帖子内容进入对应的帖子详情
    let that=this;
    let forwardId=e.currentTarget.dataset.forumid;
    let retitle = e.currentTarget.dataset.retitle;
    // wx.setStorageSync("tabNum", that.data.tabNum);
    if(forwardId != 0 && retitle != null){
      wx.navigateTo({
        url: '../detailPost/detailPost?ID=' + forwardId + "&retitle=" + retitle + 
        "&redelete=" + 1 + "&fromindex=" + 1,
      });
    }else{
      app.showNotify(that, "原贴内容不存了哦，无法查看！");
     
    }
  },  
  previewImg:function(e){//预览图片
    let src = e.currentTarget.dataset.src;//获取data-src
    let imgLists = e.currentTarget.dataset.list;//获取data-list
      //图片预览
     wx.previewImage({
       current: src, // 当前显示图片的http链接
       urls: imgLists // 需要预览的图片http链接列表
    })
  },
  delForum:function(e){//删除帖子按钮
     let that=this;
     let delforums={};
     let index = e.currentTarget.dataset.index;
     delforums.ID=e.currentTarget.dataset.id;
     delforums.UserId=app.getStorage('customerId');
     that.setData({delforums:delforums,delArea:false,index:index});
  },
  delForumaction:function(e){//删除帖子
     let that=this;
     let index=that.data.index;
     httptool.ajaxPost("api/Topic/DelTopic",that.data.delforums, function (res) {
        if (res.suc) {
          that.data.topics.splice(index, 1);
          that.setData({ topics: that.data.topics,delArea:true});
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          });
        }else{
              app.showNotify(that, res.msg);
            }
        });
  },
  upTop:function(e){//置顶帖子
     let that=this;
     let upForum={};
     upForum.ID=e.currentTarget.dataset.id;
     upForum.UserId=app.getStorage('customerId');
     httptool.ajaxPost("api/Topic/AddTopicTop",upForum, function (res) {
        if (res.suc) {
          wx.showToast({
            title: '置顶成功',
            icon: 'success',
            duration: 2000
          });
          setTimeout(function(){
            that.getTopics();
          },2000);         
        }else{
              app.showNotify(that, res.msg);
            }
        });

  },
  /** 删除帖子时**/
  closeDel:function(e){
    let that=this;
    that.setData({delArea:true});
  },
  canDel:function(e){//取消
    let that=this;
    that.setData({delArea:true});
  },
  delAction:function(e){//确定删除
    let that=this;
    that.delForumaction();
  },
  /** 删除帖子结束**/
  daLei:function(e){
    let self = this;
    httptool.login(function () {
      tabjs.daleiBtnClick();
    });  
  },
  registerBtn: function (e) {
    wx.setStorageSync("tabNum", this.data.tabNum);
    wx.navigateTo({
      url: '../register/register',
    })
  },
  myCenter: function (e) {
    wx.setStorageSync("tabNum", this.data.tabNum);
    wx.redirectTo({
      url: '../myCenter/myCenter',
    })
  },
  leiCircle: function (e) {
    wx.setStorageSync("tabNum", this.data.tabNum);
    wx.redirectTo({
      url: '../index/index',
    })
  },
})